package com.truckdispatching.image;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.os.Handler;

public class ImageUploadTask implements Runnable {

	private String mActionUrl;
	private File mUploadFile;
	private HashMap<String, String> mRequestParams;

	private Handler mImageTaskHandler;

	public ImageUploadTask(String actionUrl, HashMap<String, String> params, File file) {
		mActionUrl = actionUrl;
		mUploadFile = file;
		mRequestParams = params;
	}

	public void setUploadListener(Handler handler) {
		this.mImageTaskHandler = handler;
	}

	@Override
	public void run() {
		post(mActionUrl, mRequestParams, mUploadFile);
	}

	public void post(String actionUrl, HashMap<String, String> params, File file) {
		String BOUNDARY = "-------------------------7da2137580612";
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";

		DataOutputStream outStream = null;
		try {
			URL uri = new URL(actionUrl);
			HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

			conn.setReadTimeout(15 * 1000);
			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false);
			conn.setRequestMethod("POST"); // Post方式
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Charsert", "UTF-8");

			conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
			outStream = new DataOutputStream(conn.getOutputStream());

			if (params != null && params.size() > 0) {
				// 首先组拼文本类型的参数
				StringBuilder sb = new StringBuilder();
				for (Map.Entry<String, String> entry : params.entrySet()) {
					sb.append(PREFIX);
					sb.append(BOUNDARY);
					sb.append(LINEND);
					sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
					//				sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
					//				sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
					sb.append(LINEND);
					sb.append(entry.getValue());
					sb.append(LINEND);
				}
				outStream.write(sb.toString().getBytes(CHARSET));
			}
			// 发送文件数据
			StringBuilder sb1 = new StringBuilder();
			sb1.append(PREFIX);
			sb1.append(BOUNDARY);
			sb1.append(LINEND);
			sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINEND);
			sb1.append("Content-Type: application/octet-stream;" + LINEND);
			sb1.append(LINEND);
			outStream.write(sb1.toString().getBytes(CHARSET));

			InputStream is = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			is.close();
			outStream.write(LINEND.getBytes());

			// 请求结束标志
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(CHARSET);
			outStream.write(end_data);
			outStream.flush();
			// 得到响应码
			int res = conn.getResponseCode();
			if (res == 200) {
				InputStream in = conn.getInputStream();
				String content = getResponseString(in);
				outStream.close();
				conn.disconnect();
				mImageTaskHandler.obtainMessage(1, content).sendToTarget();
			} else {
				mImageTaskHandler.obtainMessage(2).sendToTarget();
			}
		} catch (Exception e) {
			mImageTaskHandler.obtainMessage(2).sendToTarget();
		}
	}

	/**
	 * 将流中数据作为字符串返回
	 * 
	 * @param in
	 */
	private String getResponseString(InputStream in) {
		String getStr = "";
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			int iLength = 1024;
			int bytesRead = 0;
			byte[] buff = new byte[iLength];
			while (true) {
				bytesRead = in.read(buff);
				if (bytesRead < 1) {
					break;
				}
				baos.write(buff, 0, bytesRead);
			}
			getStr = new String(baos.toByteArray(), "utf-8");
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
				}
				baos = null;
			}
		}
		return getStr;
	}
}
